package middle;

public class Solution_8 {

    public int myAtoi(String s) {
        char[] chars = s.toCharArray();
        int begin = -1, end = -1;
        boolean flag = true;
        boolean find = false;
        boolean digt = false;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] >= '0' && chars[i] <= '9') {
                digt = true;
                if (begin < 0 && chars[i] > '0') {
                    begin = i;
                }
                if (begin >= 0) {
                    end = i;
                }
            } else {
                if (digt || find || !(chars[i] == '-' || chars[i] == '+' || chars[i] == ' ')) {
                    break;
                }
                if (chars[i] == '-' || chars[i] == '+') {
                    find = true;
                    if (chars[i] == '-') {
                        flag = false;
                    }
                }
            }
        }
        if (begin < 0) {
            return 0;
        }
        long base = flag ? 1 : -1;
        long limit = flag ? Integer.MAX_VALUE : Integer.MIN_VALUE;
        long num = 0;
        for (int i = end; i >= begin; i--) {
            long add = (long) (chars[i] - '0') * base;

            if (flag) {
                if (limit - num < add || base > limit) {
                    return (int) limit;
                }
            } else {
                if (limit - num > add || base < limit) {
                    return (int) limit;
                }
            }
            num += add;
            base *= 10;
        }
        return (int) num;
    }

    public static void main(String[] args) {
        Solution_8 model = new Solution_8();
        System.out.println(model.myAtoi("20000000000000000000"));
        System.out.println(model.myAtoi("-000000000000001"));
        System.out.println(model.myAtoi("42"));
        System.out.println(model.myAtoi("   -42"));
        System.out.println(model.myAtoi("4193 with words"));
        System.out.println(model.myAtoi("words and 987"));
        System.out.println(model.myAtoi("-91283472332"));
        System.out.println(model.myAtoi("   +0 123"));
    }
}
